package com.ruoyi.grc.cach;

import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;

public class CachUtils {
    public static List getCacheList(String key){
        List cacheList = getCache(key);

        if (cacheList.size()>0)
        {
            return cacheList;
        }else {

            List dbList = getDBList(key);
            if (dbList.size()>0)
            {
                CachUtils.setCache(key, dbList);
                return dbList;
            }
        }
        return null;
    }

    public static List getDBList(String beanName){
        Map<String, ICachService> beansOfType = SpringUtil.getBeansOfType(ICachService.class);
        if(beansOfType.containsKey(beanName)){
            ICachService cachService = beansOfType.get(beanName);
            return cachService.getCachDBList();
        }else{
            throw  new RuntimeException(String.format("%s 不存在，请在选择[ %s  ] "
                    , beanName
                    ,beansOfType.keySet()
                    ));
        }

    }

    public static long clearCache(String key)
    {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(getCacheKey(key)+ "*");
        long l = SpringUtils.getBean(RedisCache.class).deleteObject(keys);
        return l;
    }


    public static void setCache(String key, List dbList)
    {
        SpringUtils.getBean(RedisCache.class).setCacheList(getCacheKey(key), dbList);
    }

    public static List getCache(String key)
    {
        List<Object> cacheList = SpringUtils.getBean(RedisCache.class).getCacheList(getCacheKey(key));
        return cacheList;

    }
    public static String getCacheKey(String configKey)
    {
        return Constants.SYS_CACH_KEY + configKey;
    }

}
